﻿using E3.CSharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace UpgradeWork
{
    public partial class frmMain : Form
    {
        public static string mCurrentPath = Application.StartupPath;
        public static string mDownLoadPath = Application.StartupPath + "\\DownLoad";

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
                string sProcessName = p.ProcessName.ToLower() + ".exe";
                if ((sProcessName == "coreshop.exe") || (sProcessName == "autoupdate.exe") || (sProcessName == "yunposexchange.exe"))
                {
                    for (int i = 0; i < p.Threads.Count; i++)  p.Threads[i].Dispose();
                    p.Kill();                    
                }
            }
        }

        private bool isZip(string fileName)
        {
            bool iszip = false;
            if (fileName.Split('.').Length > 1)
            {
                if (fileName.Split('.')[1].ToLower() == "zip")
                {
                    iszip = true;
                }
            }
            return iszip;
        }

        public void MoveFile()
        {
            bool bIsShowMsg = false;
            try
            {
                this.Refresh();
                if (Directory.Exists(mDownLoadPath) == false) return;
                this.progressBar1.Value = 0;
                try
                {      
                    bIsShowMsg = true;

                    Unzip();

                    CopyDirectory(mDownLoadPath, mCurrentPath, true);
                    DeleteDir(mDownLoadPath);
                    this.progressBar1.Value = this.progressBar1.Maximum;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("更新失败！" + ex.Message.ToString());
                    return;
                }
            }
            catch { }
            finally {
                //if (bIsShowMsg) MessageBox.Show("升级更新完成。");
                MessageBox.Show("升级更新完成。");
                Thread.Sleep(2000);
                string toolPath = Application.StartupPath + "\\CoreShop.exe";
                if (File.Exists(toolPath))
                {
                    Process.Start(toolPath);
                    //Application.Exit();
                }
                Application.Exit();
            }
        }

        //解压zip文件 到 相应路径
        private void Unzip()
        {
            if (!Directory.Exists(mDownLoadPath)) return;
            foreach (string file in Directory.GetFiles(mDownLoadPath))
            {
                if (isZip(file))
                {
                    UnZipFile(file, mDownLoadPath);
                }
            }
        }

        private bool UnZipFile(string zipFilePath, string localPath)
        {
            bool result = true;
            try
            {
                if (!File.Exists(zipFilePath))
                {
                    return false;
                }
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (!Directory.Exists(localPath))
                        {
                            Directory.CreateDirectory(localPath);
                        }
                        string subdir = theEntry.Name.LastIndexOf(fileName) == 0
                                            ? ""
                                            : theEntry.Name.Substring(0, theEntry.Name.LastIndexOf(fileName) - 1);

                        string filedir = localPath + @"\" + subdir;
                        if (!Directory.Exists(filedir))
                        {
                            Directory.CreateDirectory(filedir);
                        }

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(localPath + @"\" + theEntry.Name))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        public static void DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

                //去除文件的只读属性
                System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);

                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (File.Exists(f))
                        {
                            //如果有子文件删除文件
                            File.Delete(f);
                            Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }

                    //删除空文件夹
                    Directory.Delete(file);
                    Console.WriteLine(file);
                }

            }
            catch (Exception ex) // 异常处理
            {
                Console.WriteLine(ex.Message.ToString());// 异常信息
            }
        }

        private bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
        {
            bool ret = false;
            try
            {
                SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
                this.progressBar1.Maximum = Directory.GetFiles(mDownLoadPath).Length + 2;
                this.Refresh();
                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false)
                        Directory.CreateDirectory(DestinationPath);

                    foreach (string fls in Directory.GetFiles(SourcePath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);

                        if (this.progressBar1.Value < this.progressBar1.Maximum)
                            this.progressBar1.Value = this.progressBar1.Value + 1;
                    }
                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
                            ret = false;
                    }
                }
                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }

        private void frmMain_Shown(object sender, EventArgs e)
        {
            this.Refresh();
            Thread.Sleep(2000);
            MoveFile();
        }
    }
}
